package cn.support.neo.mvp.core.service.intercaptor;

import android.content.Context;

import com.github.pwittchen.prefser.library.Prefser;

import java.io.IOException;

import cn.support.neo.mvp.core.base.Constants;
import okhttp3.Interceptor;
import okhttp3.Response;
import rx.Observable;
import rx.functions.Action1;
import rx.functions.Func1;

/**
 * Name:Cookie拦截器
 * Author: WK（wangkun@xjzhicheng.com)
 * Date: 2016-06-30
 * Describe: PLEASE TO FIXME...
 */
public class GetCookieInterceptor implements Interceptor {

    private Context context;

    public GetCookieInterceptor(Context context) {
        super();
        this.context = context;
    }

    @Override
    public Response intercept(Chain chain) throws IOException {
        Response originalResponse = chain.proceed(chain.request());
        if (!originalResponse.headers("Set-Cookie").isEmpty()) {
            final StringBuffer cookieBuffer = new StringBuffer();
            Observable.from(originalResponse.headers("Set-Cookie"))
                    .map(new Func1<String, String>() {
                        @Override
                        public String call(String s) {
                            String[] cookieArray = s.split(";");
                            return cookieArray[0];
                        }
                    })
                    .subscribe(new Action1<String>() {
                        @Override
                        public void call(String cookie) {
                            cookieBuffer.append(cookie).append(";");
                        }
                    });
            Prefser prefser = new Prefser(context);
            prefser.put(Constants.GUEST_SESSION_KEY, cookieBuffer.toString());
        }
        return originalResponse;
    }

}
